package com.xxx.client.handler;

import com.xxx.request.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 * Created by louisyuu on 2020/4/30 上午10:10
 */
public class ChannelBoundHandler extends ChannelInboundHandlerAdapter implements Callable {
    private volatile ChannelHandlerContext context;
    private String result;
    private RpcRequest param;


    public void channelActive(ChannelHandlerContext ctx) {
        context = ctx;
    }

    /**
     * 收到服务端数据，唤醒等待线程
     */

    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (context.channel().isActive()) {
            result = msg.toString();
        }
        notify();
    }

    /**
     * 写出数据，开始等待唤醒
     */

    public synchronized Object call() throws InterruptedException {

        System.out.println("=====Current channel is active：" + context.channel().isActive());
        if (context.channel().isActive()) {
            context.writeAndFlush(param);
            wait();
            return result;
        }
        return null;
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        context = ctx;
//        System.out.println("======Channel unregistered");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        context = ctx;
//        System.out.printf("\n=====Chanel %s is inactive", ctx.channel().remoteAddress());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        super.channelWritabilityChanged(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        context = ctx;
        System.out.println("=====Chanel exception caught");
    }

    /*
     设置参数
     */

    public void setParam(RpcRequest param) {
        this.param = param;
    }

    public ChannelHandlerContext getContext() {
        return context;
    }

    public String getResult() {
        return result;
    }

    public RpcRequest getParam() {
        return param;
    }
}
